package com.umeox.iqibla.custom_tasbih.ui

import android.app.KeyguardManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.PowerManager
import android.view.Window
import com.umeox.iqibla.custom_tasbih.R
import com.umeox.iqibla.custom_tasbih.base.BaseApp
import com.umeox.moto.common.log.Logger
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity

class TriggerActivity: ThemeAppCompatActivity() {

    private var kl: KeyguardManager.KeyguardLock? = null
    private var wakeLock: PowerManager.WakeLock? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_trigger)
        wakeUpAndUnlock()
        enableHomeKeyDispatched(window, true)
    }

    private fun wakeUpAndUnlock() {
        if (kl == null) {
            val km = getSystemService(KEYGUARD_SERVICE) as KeyguardManager
            kl = km.newKeyguardLock("unLock")
        }
        //解锁
        kl!!.disableKeyguard()
        if (wakeLock == null) {
            val pm = getSystemService(POWER_SERVICE) as PowerManager
            wakeLock = pm.newWakeLock(
                PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.FULL_WAKE_LOCK,
                javaClass.simpleName
            )
        }
        // 点亮亮屏
        wakeLock!!.acquire()
        Handler(Looper.getMainLooper()).postDelayed({
            releaseLock()
        },5 *1000)
    }



    private fun enableHomeKeyDispatched(window: Window, enable: Boolean) {
        val lp = window.attributes
        if (enable) {
            lp.flags = lp.flags or -0x80000000
        } else {
            lp.flags = lp.flags and (-0x80000000).inv()
        }
        window.attributes = lp
    }

    private fun releaseLock() {
        if (wakeLock != null) {
            try {
                wakeLock!!.release()
            } catch (th: Throwable) {
                th.stackTrace
            } finally {
                wakeLock = null
            }
        }
    }

    override fun onDestroy() {
        Logger.e("===============onDestroy=======================")
        releaseLock()
        BaseApp.schedulePrayerTimeAlarm()
        super.onDestroy()
    }

    override fun onBackPressed() {
        super.onBackPressed()
        releaseLock()
    }
}